<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .item {
            border: 1px solid black;
            width: 100px;
            height: 100px;
            margin: 10px;
            float: left;
        }
    </style>
</head>
<body>
    <div class="container">
        <h3>点击切换颜色</h3>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
    </div>
    <script>
        var items = document.getElementsByClassName("item");
        /*
        for(var i=0;i<items.length;i++) {
            items[i].onclick = function() {
                //常规写法
                //this.style.background = 'pink';
                //使用items[i]报错，回调函数被调用时，i=3,超过数组范围
                items[i].style.background = 'pink';
            }
        }
        */
        for(let i=0;i<items.length;i++) {
            items[i].onclick = function() {
                //使用let i 正常，每个{}块中都有一个i，取值分别为0,1,2
                items[i].style.background = 'pink';
            }
        }
    </script>
</body>
</html>